package ncc.bs.Plugins;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.itf.pub.dbservice.IDBService;
import nc.jdbc.framework.generator.IdGenerator;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import ncc.bs.Plugins.cz.CZBusinessSQL;
import nccloud.bs.log.LogVO;
import nccloud.tool.copro.report.StringUtils;
import nccloud.utils.baseapp.HttpReqUtils;
import nccloud.utils.baseapp.InitParamUtils;
import nccloud.utils.baseapp.ToolUtils;

/** 
 * <p>同步财政系统</p>
 *  单位会计凭证主表
 * @author Administrator
 * @date 2024年2月27日
 */
public class VoucherBackGroundWorkPlugin extends AbstractBackgroundWorkPlugin{
	private BaseDAO dao;
	private final SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat ymdsfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private IDBService dbService;

	@SuppressWarnings({ "rawtypes", "unused" })
	@Override
	public void doBusiness(Map keyMap) throws BusinessException {
		String sql = CZBusinessSQL.builderCZ_GLA_VOU_HEAD(keyMap);
		List<Map<String, Object>> lists = queryData(sql);
		try {
			if(lists == null ) return;
			// 对分组的数据进行推送
			for(Map<String, Object> map : lists) {
				List<LogVO> listVOs = new ArrayList<>();
				String message = null;
				String issuccess = "Y";
				String result = null;
				try {
					String param = super.getParam(buildParam(map,listVOs),"DWKJHS05", super.getAppid()); // 每十行数据合并在一起推送
					if(param == null || "".equals(param)) return;
					if(param == null) return;
					result = HttpReqUtils.sendPost(getURL("DEF001"), param);
					getLog().info("----第四步接口响应结果::" + result);
					JSONObject jsonres = JSONObject.parseObject(result);
					Object code = jsonres.get("code");
					if("200".equals(code)) {
						message = "同步成功";
					}else {
						message = jsonres.getString("msg"); 
						issuccess = "N";
						result = jsonres.toString();
					}
					
				}catch(Exception e) {
					message = e.getMessage();
					issuccess = "N";
					getLog().error("凭证主表同步异常:【"+message+"】");
				}finally {
					for(LogVO vo : listVOs) {
						vo.setIssuccess(issuccess);
						vo.setError(message);
						vo.setVdef2(result);
						
					}
					getDbService().insertVOList(listVOs);
				}
			}
		}catch(Exception e) {
			LogVO vo = new LogVO();
			vo.setPk_id(NCLocator.getInstance().lookup(IdGenerator.class).generate());
			vo.setIssuccess("N");
			vo.setPk_group("0001A210000000000JB9");
			vo.setPk_billtypeid("accountSubject");
			vo.setSystem_flag("financial");
			vo.setVdef1("拉取参数、类型:"+ keyMap.get("type")+",开始日期:"+keyMap.get("begindate")+"结束日期:"+keyMap.get("enddate")+",同步频率:"+keyMap.get("synctime"));
			vo.setError("会计科目同步:"+e.getMessage());
			getDbService().insertVO(vo);
		}
	}

	/**
	 * 查询需要同步的数据
	 * @param sql
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>>  queryData(String sql)  throws BusinessException{
		if(sql == null) return null;
		List<Map<String, Object>> lists = (List<Map<String, Object>>)getDao().executeQuery(sql, new MapListProcessor());
		return lists == null ||  lists.isEmpty() ? null : lists;
	}

	/**
	 * 构建请求参数
	 * @return
	 * @throws Exception 
	 */
	public JSONArray buildParam(Map<String, Object> map,List<LogVO> listVOs) throws Exception{
		if(map == null) return null;
		JSONArray jsonArray = new JSONArray();
		JSONObject json = new JSONObject();
		json.put("VOU_ID", ToolUtils.getJudgeAttribute(map.get("vou_id")));  // 凭证主表唯一标识
		json.put("MOF_DIV_CODE", super.getMOF_DIV_CODE()); // 财政区划代码
		json.put("SET_YEAR", ToolUtils.getJudgeAttribute(map.get("set_year"))); // // 会计年度
		json.put("ACCT_SET_CODE", super.getAccount());  // 账套编号
		json.put("AGENCY_CODE", super.getUnit()); // 单位代码
		json.put("ACCT_SET_NAME", super.getACCT_SET_NAME());  // 账套名称
		json.put("AGENCY_NAME", super.getAGENCY_NAME()); // 单位名称
		json.put("AGENCY_ACCT_VOUCHER_TYPE", "JZ");
		json.put("AGENCY_ACCT_VOUCHER_NAME", "记账"); // 单位会计记账凭证类型
		json.put("VOUCHER_NO", ToolUtils.getJudgeAttribute(map.get("voucher_no"))); // 凭证号
		String VOUCHER_ABS = "";
		if (null != map.get("voucher_abs") || !"".equals(map.get("voucher_abs").toString())){
			if(map.get("voucher_abs").toString().length() > 150){
				VOUCHER_ABS = map.get("voucher_abs").toString().substring(0,150);
			}else{
				VOUCHER_ABS = map.get("voucher_abs").toString();
			}
		}
		json.put("VOUCHER_ABS", VOUCHER_ABS); // 凭证摘要
		json.put("INPUTER", ToolUtils.getJudgeAttribute(map.get("inputer"))); // 制单人
		String inputerDate = super.getYMD(map.get("inputer_date"));
		String ACCT_PERIOD = inputerDate.substring(4, 6);
		json.put("INPUTER_DATE", inputerDate); // 制单日期
		json.put("VOUCHER_DATE", inputerDate); // 记账凭证日期
		json.put("ACCT_PERIOD", ACCT_PERIOD); //会计期间
		Object AUDITOR = "".equals(ToolUtils.getJudgeAttribute(map.get("auditor"))) ? ToolUtils.getJudgeAttribute(map.get("inputer")) : ToolUtils.getJudgeAttribute(map.get("auditor"));
		json.put("AUDITOR", AUDITOR); // 审核人
		Object AUDITOR_DATE =  "".equals(super.getYMD(map.get("auditor_date"))) ? inputerDate : super.getYMD(map.get("auditor_date"));
		json.put("AUDITOR_DATE", AUDITOR_DATE); // 审核日期
		json.put("CHECKER", ToolUtils.getJudgeAttribute(map.get("checker"))); // 出纳人
		json.put("CHECKER_DATE", super.getYMD(map.get("checker_date"))); // 出纳日期
		json.put("POSTER", ToolUtils.getJudgeAttribute(map.get("poster"))); // 记账人
		Object POSTER_DATE =  "".equals(super.getYMD(map.get("poster_date"))) ? inputerDate : super.getYMD(map.get("poster_date"));
		json.put("POSTER_DATE", POSTER_DATE); // 记账日期
		Object FI_LEADER = "".equals(ToolUtils.getJudgeAttribute(map.get("fi_leader"))) ? ToolUtils.getJudgeAttribute(map.get("inputer")): ToolUtils.getJudgeAttribute(map.get("fi_leader"));
		json.put("FI_LEADER", FI_LEADER); // 财务负责人
		json.put("CR_AMT", map.get("cr_amt") == null ? 0 : map.get("cr_amt")); // 财务贷方金额
		json.put("DR_AMT", map.get("dr_amt") == null ? 0 : map.get("dr_amt")); // 财务借方金额
		Object CR_YS_AMT = map.get("cr_ys_amt") == null ? 0 : map.get("cr_ys_amt") ;
		Object DR_YS_AMT = map.get("dr_ys_amt") == null ? 0 : map.get("dr_ys_amt");
		json.put("CR_YS_AMT", CR_YS_AMT); // 预算贷方金额
		json.put("DR_YS_AMT", DR_YS_AMT); // 预算借方金额
		String sql = "select count(*) from sm_pub_filesystem where isfolder = 'n' and filepath like '"+map.get("vou_id")+"%'";
		json.put("VOU_CNT", map.get("attachment")); // 附件数
		json.put("RED_FLAG", map.get("red_flag")); // 红冲状态
		json.put("RED_VOU_NO", ToolUtils.getJudgeAttribute(map.get("red_vou_no"))); // 红冲记账凭证号
		json.put("IS_ADJUST_PERIOD", ToolUtils.getJudgeAttribute(map.get("is_adjust_period"))); // 是否调整期
		json.put("VOU_STATUS", 1); // 凭证状态
		Object IS_CARRY_OVER = "".equals(ToolUtils.getJudgeAttribute(map.get("is_carry_over"))) ? 1 : ToolUtils.getJudgeAttribute(map.get("is_carry_over"));
		json.put("IS_CARRY_OVER", IS_CARRY_OVER); // 是否为结转凭证
		json.put("UPDATE_TIME", super.getYMDHMS(map.get("update_time"))); // 更新时间
		json.put("CREATE_TIME", super.getYMDHMS(map.get("create_time")));
		json.put("IS_DELETED", map.get("is_deleted")); // 1已删除 2 未删除
		LogVO logVO = getDbService().buildLogVO(map, json, "financial", "voucher");
		listVOs.add(logVO);
		jsonArray.add(json);
		return jsonArray;
	}
	
	/**
	 * 获取第三方同步地址
	 * @param initCode
	 * @return
	 * @throws Exception
	 */
	public String getURL(String initCode) throws Exception{
		String url = InitParamUtils.getOrgParam("GLOBLE00000000000000",initCode)+"/pty/gla-dec/v1/voucher/vouchers";
		getLog().info("----第三步接口请求地址:" + url);
		return url;
	}

	/**
	 * 数据库操作服务
	 * @return
	 */
	public IDBService getDbService() {
		if(dbService == null) {
			dbService = NCLocator.getInstance().lookup(IDBService.class);
		}
		return dbService;
	}

	public BaseDAO getDao() {
		return dao == null ? new BaseDAO() : dao ;
	}
}
